package edu.ccut.saturn.basecomponent.database.facade;

import java.sql.Connection;

import edu.ccut.saturn.basecomponent.database.IDeleteSQLBuilder;
import edu.ccut.saturn.basecomponent.database.ISaturnSQL;
import edu.ccut.saturn.basecomponent.database.ISaturnSQLBuilder;
import edu.ccut.saturn.basecomponent.database.SaturnSQLBuilderFactory;
import edu.ccut.saturn.basecomponent.database.SaturnSQLHandler;
import edu.ccut.saturn.basecomponent.database.util.SaturnDataUtil;
import edu.ccut.saturn.component.IDataItem;
import edu.ccut.saturn.component.SaturnComponentException;

public class DeleteByPrimaryKey {
	public int execute(String fullKey,String primaryKeyValue,Connection conn) throws Exception {
		String dbType = SaturnDataUtil.getStandardDBType(fullKey);
		ISaturnSQLBuilder builder = SaturnSQLBuilderFactory.getSaturnSQLBuilder(dbType);
		if(builder!=null){
			if (primaryKeyValue == null) {
				throw new SaturnComponentException(
						"PrimaryKeyValue can not be null !");
			}
			IDataItem item = SaturnDataUtil.getPKDataItem(fullKey);
			if (item == null) {
				throw new SaturnComponentException(
						"Can not find primaryKey in SaturnData name is" + fullKey);
			}
			String condition = " WHERE " + item.getColumn() + " ='" + primaryKeyValue + "' ";
			IDeleteSQLBuilder sqlBuilder = builder.getDeleteSQLBuilder(ISaturnSQL.DELETE_OPERATION);
			ISaturnSQL saturnSQL = sqlBuilder.build(fullKey, condition);
			int count = SaturnSQLHandler.executeUpdate(saturnSQL, conn);
			return count;
		}
		return 0;
	}
}
